summaryrefslogtreecommitdiff
path: root/src-migrate/pages/api/product-variant/[id]/promotion/[category].tsx
blob: 8da0d9a34f4ef844e25c2bda7fde605b841d099f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { NextApiRequest, NextApiResponse } from "next";
import { SolrResponse } from "~/types/solr";

const SOLR_HOST = process.env.SOLR_HOST as string

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const productId = req.query.id as string
  const category = req.query.category as string

  if (req.method === 'GET') {
    const queryParams = new URLSearchParams({ q: `product_ids:${productId}` })
    queryParams.append('fq', `type_value_s:${category}`)
    queryParams.append('fq', `active_b:true`)

    const response = await fetch(`${SOLR_HOST}/solr/promotion_program_lines/select?${queryParams.toString()}`)
    const data: SolrResponse<any[]> = await response.json()

    const promotions = await map(data.response.docs)
    res.status(200).json({ data: promotions })
  }
}

const map = async (promotions: any[]) => {
  const result = []

  for (const promotion of promotions) {
    const data: any = {}

    data.id = promotion.id
    data.program_id = promotion.program_id_i
    data.name = promotion.name_s
    data.type = {
      value: promotion.type_value_s,
      label: promotion.type_label_s,
    }
    data.limit = promotion.package_limit_i
    data.limit_user = promotion.package_limit_user_i
    data.limit_trx = promotion.package_limit_trx_i
    data.price = promotion.price_f
    data.total_qty = promotion.total_qty_i

    data.products = JSON.parse(promotion.products_s)
    data.free_products = JSON.parse(promotion.free_products_s)

    result.push(data)
  }

  return result
}